<script setup lang="ts">

import {onMounted, ref, useTemplateRef} from "vue";
import myAxios from "../../plugins/MyAxios";
import {showFailToast, showSuccessToast} from "vant";
import router from "../../router";
import { items, show, tagsMap } from "../../common/treeSelectList.ts";

const activeIds = ref([]);
const activeIndex = ref(0);

class User {
  id: number
  username: string
  userAccount: string
  userPassword: string
  gender: number
  avatarUrl: string
  phone: string
  email: string
  userRole: number
  wheatCode: string
  tags: string

  constructor(
      id: number = 0,
      username: string = '',
      userAccount: string = '',
      userPassword: string = '',
      gender: number = 0,
      avatarUrl: string = '',
      phone: string = '',
      email: string = '',
      userRole: number = 0,
      wheatCode: string = '',
      tags: string = ''
  ) {
    this.id = id;
    this.username = username;
    this.userAccount = userAccount;
    this.userPassword = userPassword;
    this.gender = gender;
    this.avatarUrl = avatarUrl;
    this.phone = phone;
    this.email = email;
    this.userRole = userRole;
    this.wheatCode = wheatCode;
    this.tags = tags;
  }
}

const currentUser = ref<User | null>(null);
const id = ref()
const username = ref()
const gender = ref()
const phone = ref()
const email = ref()
const avatarUrl = ref()
const tagList = ref()
onMounted(async () => {
  try {
    const userInfo = sessionStorage.getItem('userInfo');
    const result = ref();
    if (userInfo === null) {
      result.value = await myAxios.get('/user/current');
      sessionStorage.setItem('userInfo', JSON.stringify(result.value.data.data));
      result.value = result.value.data.data
    } else {
      result.value = JSON.parse(userInfo)
    }
    const data = result.value
    // 将 API 返回的数据映射到 User 类的实例
    currentUser.value = new User(
        data.id,
        data.username,
        data.userAccount,
        data.userPassword,
        data.gender,
        data.avatarUrl,
        data.phone,
        data.email,
        data.userRole,
        data.wheatCode,
        data.tags
    );
    id.value = currentUser.value?.id || '';
    username.value = currentUser.value?.username || '';
    gender.value = formatGender(currentUser.value?.gender);
    phone.value = currentUser.value?.phone || '';
    email.value = currentUser.value?.email || '';
    avatarUrl.value = currentUser.value?.avatarUrl || '';
    tagList.value = JSON.parse(currentUser.value?.tags);
    activeIds.value = Array.from(tagList.value)
    formatTagsList(activeIds.value)
  } catch (e) {
    console.error('获取用户数据失败:', e);
  }
});

// 初始化tagsMap
function formatTagsList(tagsList : string[]) {
  tagsList.forEach(tag => {tagsMap.set(tag, 1)})
}

// 格式化性别
function formatGender(gender: any) {
  switch (gender) {
    case 0:
      return '女';
    case 1:
      return '男';
    default:
      return '未知';
  }
}

// 格式化角色
function formatRole(role: any) {
  switch (role) {
    case 0:
      return '普通用户';
    case 1:
      return '管理员';
    default:
      return '未知';
  }
}

// 格式化请求性别设置
function formatGenderToRequest(changeGender: string) {
  switch (changeGender) {
    case '男' : {
      return 1;
    }
    case '女' : {
      return 0;
    }
    default : {
      return null;
    }
  }
}

const showBottom = ref(false)
const showChange = ref(false)
const showPopup = () => {
  showBottom.value = true;
}

const columns = [
  {text: '头像', value: 'avatarUrl'},
  {text: '昵称', value: 'username'},
  {text: '性别', value: 'gender'},
  {text: '手机号', value: 'phone'},
  {text: '邮箱', value: 'email'},
  {text: '标签', value: 'tags'}
];

const onCancel = () => {
  showBottom.value = false;
}

const showWhich = ref('')
const isShowUpdateUserName = ref<boolean>(false)
const isShowUpdateGender = ref<boolean>(false)
const isShowUpdatePhone = ref<boolean>(false)
const isShowUpdateEmail = ref<boolean>(false)
const isShowUpdateTags = ref<boolean>(false)
const showChangeAvatarUrl = ref<boolean>(false)
const onConfirm = (values: any) => {
  showChange.value = true;
  showWhich.value = values.selectedValues[0];
  switch (showWhich.value) {
    case 'avatarUrl' : {
      showChangeAvatarUrl.value = true;
      break;
    }
    case 'username' : {
      isShowUpdateUserName.value = true;
      break;
    }
    case 'gender' : {
      isShowUpdateGender.value = true;
      break;
    }
    case 'phone' : {
      isShowUpdatePhone.value = true;
      break;
    }
    case 'email' : {
      isShowUpdateEmail.value = true;
      break;
    }
    case 'tags' : {
      isShowUpdateTags.value = true;
      break;
    }
    default : {
      showChange.value = false;
      break;
    }
  }
}

const resetIsShowUpdate = () => {
  switch (showWhich.value) {
    case 'username' : {
      isShowUpdateUserName.value = !isShowUpdateUserName.value;
      break;
    }
    case 'gender' : {
      isShowUpdateGender.value = !isShowUpdateGender.value;
      break;
    }
    case 'phone' : {
      isShowUpdatePhone.value = !isShowUpdatePhone.value;
      break;
    }
    case 'email' : {
      isShowUpdateEmail.value = !isShowUpdateEmail.value;
      break;
    }
    case 'tags' : {
      isShowUpdateTags.value = !isShowUpdateTags.value;
      break;
    }
  }
}

const form = useTemplateRef('form');
const updateInfo = async () => {
  try {
    const tagsList = Array.from(tagsMap)
        .filter(([, value]) => value % 2 !== 0)
        .map(([key]) => key);
    const tagsString = `[${tagsList.map(tag => `"${tag}"`).join(", ")}]`;
    const formRef = form.value as any;
    await formRef.validate();
    const result = await myAxios.post('/user/updateUser', {
      id: id.value,
      username: username.value,
      gender: formatGenderToRequest(gender.value),
      avatarUrl: avatarUrl.value,
      phone: phone.value,
      email: email.value,
      tags: tagsString
    })
    if (result.data.code === 200) {
      showChange.value = false;
      showBottom.value = false;
      showSuccessToast('更新成功');
    }
  } catch (e) {
    showFailToast('更新失败');
    console.log(e)
  }
}

// 上传更新用户头像
const fileObj = ref();
const fileList = ref<{ url: string, isImage: boolean }[]>([]);
const afterRead = (file: any) => {

  fileList.value.push({
    url: file.objectUrl,
    isImage: true
  });
  fileList.value.pop()
  // 获取图片对象
  fileObj.value = file.file
};

const updateAvatarUrl = async () => {
  if (fileObj.value === null) {
    showFailToast('图片为空');
    return;
  }
  const formData = new FormData(); // 创建 FormData 对象
  formData.append('file', fileObj.value); // 添加文件
  formData.append('id', id.value); // 添加用户 ID

  try {
    const response = await myAxios.post('/user/updateAvatarUrl', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    if (response.data.code === 200) {
      showChangeAvatarUrl.value = false;
      avatarUrl.value = response.data.data;
      showSuccessToast('更新成功');
    }
  } catch (error) {
    showFailToast('更新失败');
    console.error('错误:', error);
  }
}

const logout = async () => {
  try {
    const result = await myAxios.post('/user/logout')
    if (result.data.code === 200) {
      showSuccessToast("账号已登出！")
      sessionStorage.clear()
      await router.push('/')
    }
  } catch (e) {
    showFailToast("账号登出失败！")
    console.log(e)
  }
}
</script>

<template>
  <van-notice-bar
      left-icon="volume-o"
      text="修改用户信息后，重新登录即可看到修改后效果！"
  />

  <van-cell-group>
    <van-cell title="头像">
      <van-image width="100" height="100" :src="avatarUrl" fit="cover"></van-image>
    </van-cell>
    <van-cell title="昵称" :value="currentUser?.username ?? '未设置'"/>
    <van-cell title="账号" :value="currentUser?.userAccount ?? '未设置'"/>
    <van-cell title="性别" :value="formatGender(currentUser?.gender)"/>
    <van-cell title="手机号" :value="currentUser?.phone ?? '未设置'"/>
    <van-cell title="邮箱" :value="currentUser?.email ?? '未设置'"/>
    <van-cell title="角色" :value="formatRole(currentUser?.userRole)"/>
    <van-cell title="Wheat Code" :value="currentUser?.wheatCode ?? '未设置'"/>
    <van-cell title="标签">
      <van-tag plain type="primary" v-for="tag in tagList" style="margin-left: 5px">{{ tag }}</van-tag>
    </van-cell>
  </van-cell-group>
  <div>
    <van-cell title="修改信息" is-link @click="showPopup"/>
    <!--    第一层：用户选择修改信息选项 是否弹出：showBottom -->
    <van-popup
        v-model:show="showBottom"
        position="bottom"
        :style="{ height: '50%' }"
    >
      <van-picker
          title="修改的选项"
          :columns="columns"
          @confirm="onConfirm"
          @cancel="onCancel"
      />
    </van-popup>
    <!--    第二层：修改第一层选择的信息选项（不包含头像） 是否弹出：showChange-->
    <van-popup
        v-model:show="showChange"
        closeable
        @close="resetIsShowUpdate"
        position="bottom"
        :style="{ height: '65%' }"
    >
      <div style="margin-top: 15%">
        <van-form ref="form">
          <van-cell-group inset>
            <van-field
                v-model="username"
                v-if="isShowUpdateUserName"
                name="用户名"
                label="用户名"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '用户名填写不正确' }]"
            />
            <van-field
                v-model="gender"
                v-if="isShowUpdateGender"
                name="性别"
                label="性别"
                placeholder="请输入性别"
                :rules="[{ required: true, message: '性别只能为男或女' }]"
            />
            <van-field
                v-model="phone"
                v-if="isShowUpdatePhone"
                name="电话"
                label="电话"
                placeholder="请输入电话号码"
                :rules="[{ required: true, message: '电话号码填写不正确' }]"
            />
            <van-field
                v-model="email"
                v-if="isShowUpdateEmail"
                name="邮箱"
                label="邮箱"
                placeholder="请输入邮箱"
                :rules="[{ required: true, message: '邮箱填写不正确' }]"
            />
          </van-cell-group>
          <van-tree-select
              v-if="isShowUpdateTags"
              v-model:active-id="activeIds"
              v-model:main-active-index="activeIndex"
              :items="items"
              @click-item="show"
              max="7"
          />
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" @click="updateInfo">
              更新
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
  <!--    第二层：修改头像 是否弹出：showChangeAvatarUrl-->
  <van-popup
      v-model:show="showChangeAvatarUrl"
      closeable
      @close="() => {
        showChangeAvatarUrl = false;
        showChange = false;
      }"
      position="bottom"
      :style="{ height: '65%' }"
  >
    <div style="margin-top: 15%">
      <van-uploader v-model="fileList" :after-read="afterRead" max-count="1" style="margin-left: 40%"/>
      <div style="margin: 16px;">
        <van-button round block type="primary" @click="updateAvatarUrl">
          更新
        </van-button>
      </div>
    </div>
  </van-popup>
  <div style="margin: 16px;">
    <van-button round block type="danger" @click="logout">
      退出登录
    </van-button>
  </div>
</template>

<style scoped>

</style>